import axios from 'axios'
import router from '@/router'
import qs from 'qs'
import merge from 'lodash/merge'
import store from '@/store'
import resultCode from '@/utils/resultCode'
import { getToken, getRefreshToken } from '@/utils/auth'
import { Message } from 'element-ui'

// 创建axios实例
const http = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  withCredentials: true, // 跨域请求，允许保存cookie
  timeout: 5000, // 请求超时时间
  headers: { // application/json; charset=utf-8 //application/x-www-form-urlencoded; charset=utf-8
    'Content-Type': 'application/json; charset=utf-8'
  }
})

// request拦截器
http.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      config.headers['refresh_token'] = getRefreshToken() // 为了可以自动刷新token，一旦token过期，可以利用refreshToken刷新
    }
    return config
  },
  error => {
    // Do something with request error
    console.log('=======interceptors.request=======')
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response 拦截器
http.interceptors.response.use(
  (response) => {
    // 401, 认证无效 token失效
    if (response.status === 401) {
      store.dispatch('FedLogOut')
      router.push({ name: 'login' })
      return response
    }
    // 业务调用不成功
    console.log('=========response============')
    console.log(response)
    if (response.data && response.data.code !== resultCode.SUCCESS) {
      Message({
        message: response.data.message,
        type: 'error',
        duration: 1000
      })
      return Promise.reject('error')
    } else { // 业务调用成功
      const refresh = response.headers['refresh']
      console.log('---------refresh = ' + refresh)
      if (refresh) { // 如果token刷新了，需要把token保存到前端
        const authorization = response.headers['authorization']
        console.log('----------authorization=' + authorization)

        let access_token = null
        if (authorization.substr(0, 7) === 'Bearer ') {
          access_token = authorization.substring(7, authorization.length)
        } else {
          access_token = authorization
        }

        const refresh_token = response.headers['refresh_token']
        store.dispatch('RefreshToken', { access_token, refresh_token })
        console.log('------------RefreshToken store end---------')
      }

      return response
    }
  },
  (err) => {
    console.log('========err2==========')
    console.log(err)
    if (err && err.response) {
      Message({
        message: err.response.data.message,
        type: 'error',
        duration: 1000
      })
    } else {
      console.log('========err1==========')
      console.log(err)
      Message({
        message: err.message,
        type: 'error',
        duration: 1000
      })

      store.dispatch('FedLogOut')
      router.push({ name: 'login' })
    }

    return Promise.reject(err)
  }
)

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName) => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  return (process.env.NODE_ENV !== 'production' && process.env.OPEN_PROXY ? '/proxyApi/' : process.env.BASE_API) + actionName
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
  var defaults = {
    't': new Date().getTime()
  }
  return openDefultParams ? merge(defaults, params) : params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
  var defaults = {
    't': new Date().getTime()
  }
  data = openDefultdata ? merge(defaults, data) : data
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}

export default http
